package com.lill.sale.web;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lill.common.component.util.PageUtils;
import com.lill.common.component.util.Query;
import com.lill.common.component.util.R;
import com.lill.org.constant.PositionType;
import com.lill.sale.model.SaleBookModel;
import com.lill.sale.service.ISaleBookService;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.model.SysUserEntity;

/**
 * 销售台账Controller
 *
 * @author lill
 * @date 2021-09-25 11:41:47
 */
@RestController
@RequestMapping("sale/book")
public class SaleBookController {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
    @Autowired
    private ISaleBookService saleBookService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity user) {
    	params.put("companyId", user.getCompanyId());
    	params.put("branchId", user.getBranchId());
    	if(StringUtils.isNotEmpty(user.getPosition())&&user.getPosition().equals(PositionType.SALE.getVal())){
    		params.put("personId", user.getPersonId());
    	}
        //查询列表数据
        Query query = new Query(params);

        List<SaleBookModel> saleBookList = saleBookService.queryList(query);
        int total = saleBookService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(saleBookList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
    	SaleBookModel saleBook = saleBookService.queryObject(id);
        return R.ok().put("saleBook", saleBook);
    }
    
    @RequestMapping("/printDetail")
    public void printDetail(@RequestParam String id,HttpServletResponse res) {
    	XWPFDocument docWord=null;
    	OutputStream outDown=null;
    	try {
    		docWord=saleBookService.downLoadBookData(id);
    		res.reset();
    		String filename=URLEncoder.encode("合同信息", "UTF-8");
    		res.addHeader("Content-Disposition", "attachment;filename="+filename+".docx");
    		res.setContentType("application/octet-stream");
			outDown=res.getOutputStream();
			docWord.write(outDown);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}finally{
			try {
				if(null!=docWord){
					docWord.close();
				}
				if(null!=outDown){
					outDown.close();
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody SaleBookModel saleBook,@CurrentUser SysUserEntity user) {
    	saleBook.setPersonId(user.getPersonId());
    	saleBook.setState(1);
    	saleBook.setStatus(1);
    	saleBook.setCreateUser(user.getId());
    	saleBook.setCreateTime(new Date());
    	saleBook.setUpdateUser(user.getId());
    	saleBook.setUpdateTime(new Date());
        int result=saleBookService.save(saleBook);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody SaleBookModel saleBook,@CurrentUser SysUserEntity user) {
    	saleBook.setPersonId(user.getPersonId());
    	saleBook.setUpdateUser(user.getId());
    	saleBook.setUpdateTime(new Date());
        int result=saleBookService.update(saleBook);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }
    /**
     * 
     * @param saleBook
     * @param user
     * @return
     */
    @RequestMapping("/audityes")
    public R audityes(@RequestParam String id,@CurrentUser SysUserEntity user) {
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("updateUser", user.getId());
    	mapParam.put("updateTime", new Date());
    	mapParam.put("id", id);
    	mapParam.put("state", 1);
    	mapParam.put("newState", 2);
    	int result=saleBookService.updateSate(mapParam);
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }
    
    @RequestMapping("/auditno")
    public R auditno(@RequestParam String id,@CurrentUser SysUserEntity user) {
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("updateUser", user.getId());
    	mapParam.put("updateTime", new Date());
    	mapParam.put("id", id);
    	mapParam.put("state", 1);
    	mapParam.put("newState", 6);
    	int result=saleBookService.updateSate(mapParam);
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }
    
    @RequestMapping("/deposit")
    public R deposit(@RequestParam String id,@CurrentUser SysUserEntity user) {
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("updateUser", user.getId());
    	mapParam.put("updateTime", new Date());
    	mapParam.put("id", id);
    	mapParam.put("state", 2);
    	mapParam.put("newState", 3);
    	int result=saleBookService.updateSate(mapParam);
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }
    
    @RequestMapping("/receipt")
    public R receipt(@RequestParam String id,@CurrentUser SysUserEntity user) {
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("updateUser", user.getId());
    	mapParam.put("updateTime", new Date());
    	mapParam.put("id", id);
    	mapParam.put("state", 4);
    	mapParam.put("newState", 5);
//    	int result=saleBookService.updateSate(mapParam);
    	int result=saleBookService.updateReceipt(mapParam,user.getPersonId());
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }
    
    @RequestMapping("/cancel")
    public R cancel(@RequestParam String id,@CurrentUser SysUserEntity user) {
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("updateUser", user.getId());
    	mapParam.put("updateTime", new Date());
    	mapParam.put("id", id);
    	mapParam.put("newState", 9);
    	int result=saleBookService.cancelSate(mapParam);
    	if(result>0){
    		return R.ok();
    	}else{
    		return R.failure();
    	}
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody String[] ids,@CurrentUser SysUserEntity user) {
    	Map<String, Object> params=new HashMap<String, Object>();
    	params.put("ids", ids);
    	params.put("updateUser", user.getId());
    	params.put("updateTime", new Date());
        int result=saleBookService.deleteLogicByMap(params);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity user) {
    	params.put("companyId", user.getCompanyId());
    	params.put("branchId", user.getBranchId());
        List<SaleBookModel> list = saleBookService.queryList(params);
        return R.ok().put("list", list);
    }
}
